local desc_tgong = [[
  # 四象天宫 模式简介

  支持1~3名玩家游玩，若玩家不足3人，会有提供额外回合的人机队友陪伴。

  游戏目标：击杀星宿→击杀四神→“少昊”

  ________________

  每轮结束会正向更替一次“卦象”与“星象”

  “卦象”会决定本轮行动的BOSS

  “星象”会给予全场增益（对于BOSS来说，主场星象给与的增益是巨大的）

  游戏设有"观星"机制，当全场任意角色使用或打出满足“观星”条件的卡牌累计7次即可令“星象”正向更替


]]

-- FIXME: Disable same convert by param or extra data
local LangAI = require "packages/tshu/AI/LangAI"
local T = require "packages/tshu/record/Theorem"
local U = require "packages/utility/utility"

local tgong_getLogic = function()
  local tgong_logic = GameLogic:subclass("tgong_logic")
  
  --保留印记
  local nmark = {"tshu__tianshu","tshu__buff1","tshu__buff2","tshu__buff3","tshu__buff4","tshu__win","@ganlu","tgong__damage","tgong__draw","tgong__cover","tgong__shield","tgong__distance"}

  --黑名单
  local black = {"diycx__caixukun","diy__zhonghui","mouxusheng","joyo__nvwa","caopi","godsimayi","godzhangfei","godguanyu","goddengai","godlusu","os__simashi","manchong","zuoci","joy__godzuoci","simahui","sunru","lingju","xushao"}
  --白名单武将包
  local white = {"joy","jsrg","mobile","mini","mougong","offline","ol","shzl","sp","standard","standard_ex","tenyear","yj","Tdiy"}
  --少昊
  local godboss = {"tshugod__shaohao"}
  --神兽
  local ss = {"tshuss__qinglong","tshuss__zhuque","tshuss__baihu","tshuss__xuanwu"}
  --星宿
  local xx = {"tshuxx__jiaomujiao","tshuxx__kangjinlong","tshuxx__yihuoshe","tshuxx__xingrima","tshuxx__kuimulang","tshuxx__canshuiyuan","tshuxx__doumuxie","tshuxx__weiyueyan"}

  local test = false

  for _, g in ipairs(black) do
    for _, n in ipairs(Fk:getSameGenerals(g)) do
      table.insertIfNeed(black,n)
    end
  end

  function tgong_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      { "lord","loyalist", "loyalist", "renegade", "rebel", "rebel", "rebel","rebel","rebel","rebel"}
    }
  end

  function tgong_logic:prepareForStart()
    local room = self.room
    self:addTriggerSkill(GameRule)
    for _, trig in ipairs(Fk.global_trigger) do
      if trig.name ~= "mobile_effect" then  --关闭手杀特效
        self:addTriggerSkill(trig)
      end
    end
    self.room:sendLog{ type = "$GameStart" }
  end

  function tgong_logic:prepareDrawPile()
    local room = self.room
    local seed = math.random(2 << 32 - 1)
    local allCardIds = Fk:getAllCardIds()
    local blacklist = {"crossbow","indulgence","wd_rice","diy_restart"}
    local whitelist = {}
    for i = #allCardIds, 1, -1 do
      local card = Fk:getCardById(allCardIds[i])
      local name = card.name
      if (card.is_derived and not table.contains(whitelist, name)) or table.contains(blacklist, name) then
        local id = allCardIds[i]
        table.removeOne(allCardIds, id)
        table.insert(room.void, id)
        room:setCardArea(id, Card.Void, nil)
      end
    end
  
    table.shuffle(allCardIds)
    room.draw_pile = allCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
    room:doBroadcastNotify("PrepareDrawPile", seed)
  end
  
  function tgong_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = {"lord","loyalist", "loyalist", "renegade", "rebel", "rebel", "rebel","rebel","rebel","rebel"}
    table.shuffle(roles)

    local bots_t = {}
    local players_t = {}
    for i = 1, n do
      local p = room.players[i]
      if p.id < 0 then
        table.insert(bots_t,{p.id,i})
      end
      if p.id > 0 then
        table.insert(players_t,{p.id,i})
      end
    end

    local lord
    local rebel = {}
    local loyalist = {}
    local renegade = {}
    if #bots_t >= 1 then
      local lord_t = table.random(bots_t)
      local lord_player = room.players[lord_t[2]]
      lord_player.role = "lord"
      lord = lord_player
      lord_player.role_shown = true
      room:broadcastProperty(lord_player, "role")
      for i = 1, n do
        local p = room.players[i]
        if p.role ~= "lord" then
          if p.id < 0 then
            if #loyalist < 6 then
                p.role = "loyalist"
                table.insertIfNeed(loyalist,p)
            else
                p.role = "renegade"
                table.insertIfNeed(renegade,p)
            end
          else
            p.role = "rebel"
            table.insertIfNeed(rebel,p)
          end
          p.role_shown = true
          room:notifyProperty(p, p, "role")
        end
      end
    else
      --默认主反模式
      for i = 1, n do
        local p = room.players[i]
        p.role = roles[i]
        if p.role == "lord" then
          p.role_shown = true
          room:broadcastProperty(p, "role")
        else
          room:notifyProperty(p, p, "role")
        end
      end
    end
    table.shuffle(rebel)
    local targets = {}
    if #renegade == 2 then
        targets[1] = renegade[1]
        targets[2] = rebel[1]
        targets[3] = renegade[2]
    elseif #renegade == 1 then
        targets[1] = rebel[1]
        targets[2] = renegade[1]
        targets[3] = rebel[2]
    elseif #renegade == 0 then
        targets[1] = rebel[1]
        targets[2] = rebel[2]
        targets[3] = rebel[3]
    end
    targets[4] = loyalist[1]
    targets[5] = loyalist[2]
    targets[6] = loyalist[3]
    targets[7] = lord
    targets[8] = loyalist[4]
    targets[9] = loyalist[5]
    targets[10] = loyalist[6]
    room.players = targets
    local player_circle = {}
    for i = 1, #room.players do
      room.players[i].seat = i
      table.insert(player_circle,room.players[i].id)
    end
    for i = 1, #room.players - 1 do
      room.players[i].next = room.players[i + 1]
    end
    room.players[#room.players].next = room.players[1]
    room:doBroadcastNotify("ArrangeSeats", json.encode(player_circle))
    room.current = targets[1]
  
  end
  --选将
  function tgong_logic:chooseGenerals()
    local room = self.room ---@type Room
    local n = room.settings.generalNum
    local gpile = table.simpleClone(room.general_pile)
    for _, g in ipairs(gpile) do
      if not table.contains(white,Fk.generals[g].package.extensionName) or table.contains(black,g) then
        table.removeOne(room.general_pile,g)
      end
    end
    local rebel = {}
    local renegade = {}
    for _, p in ipairs(room.players) do
      if p.role == "renegade"   then
        table.insert(renegade,p)
      elseif p.role == "rebel" then
        table.insert(rebel,p)
      end
    end
    --二次换位
    local targets = {}
    targets[1] = room.players[5]
    targets[2] = room.players[6]
    targets[3] = room.players[7]
    targets[4] = room.players[8]
    targets[5] = room.players[9]
    targets[6] = room.players[10]
    targets[7] = room.players[1]
    targets[8] = room.players[2]
    targets[9] = room.players[3]
    targets[10] = room.players[4]
    room.players = targets
    local player_circle = {}
    for i = 1, #room.players do
      room.players[i].seat = i
      table.insert(player_circle,room.players[i].id)
    end
    for i = 1, #room.players - 1 do
      room.players[i].next = room.players[i + 1]
    end
    room.players[#room.players].next = room.players[1]
    room:doBroadcastNotify("ArrangeSeats", json.encode(player_circle))

    --队友手牌
    local rebel2 = {}
    for _, p in ipairs(room.players) do
        if p.role == "rebel" or p.role == "renegade" then
        table.insert(rebel2,p)
      end
    end
    for _, p in ipairs(rebel2) do
      for _, p2 in ipairs(rebel2) do
        if p2 ~= p then
          p:addBuddy(p2)
        end
      end
    end

    --卦象
    local gua = {"tshu_gua_zhen","tshu_gua_li","tshu_gua_dui","tshu_gua_kan"}
    local xingx = {"tshu__east","tshu__south","tshu__west","tshu__north"}
    local guax = math.random(1,4)
    room:setBanner("@tshu_guaxiang",gua[guax])
    room:setBanner("@[:]tshu__xingxiang",xingx[guax])
    --观星
    local h = {"","","",""}
      local ran = math.random(1,10)
      if ran == 1 then
        h[3] = table.random({"装备","基本","锦囊"})
      elseif ran <= 4 then
        h[4] = table.random({"jink","fire__slash","slash","thunder__slash","peach","analeptic","iron_chain","fire_attack","duel","lightning","ex_nihilo","nullification","savage_assault","archery_attack"})
      elseif ran <= 7 then
        h[1] = table.random({"log_club","log_heart","log_diamond","log_spade"})
      else
        h[2] = math.random(1,13)
      end
    room:setBanner("@tshu_guanxing",h)
    --选将

    --少昊
    local lord = room.players[7]
    room:setPlayerGeneral(lord,"tshugod__shaohao", true, true)
    room:broadcastProperty(lord, "role")
    room:broadcastProperty(lord, "general")
    room:broadcastProperty(lord, "kingdom")
    room:setPlayerMark(lord,"@tshu__4shen",{"tshu_east","tshu_south","tshu_west","tshu_north"})
    room:handleAddLoseSkills(lord,"tshu__gongzhu",nil)
    --四神兽
    local loyalist = {room.players[5],room.players[6],room.players[8],room.players[9]}
    table.shuffle(loyalist)
    for i = 1, 4, 1 do
        local p = loyalist[i]
        room:setPlayerGeneral(p,ss[i], true, true)
        room:broadcastProperty(p, "role")
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "kingdom")
        if ss[i] == "tshuss__qinglong" then
          room:setPlayerMark(p,"@tshu__xxiang",{"tshuxx__jiaomujiao-bj","tshuxx__kangjinlong-bj"})
          room:handleAddLoseSkills(p,"tshu__muzhen",nil)
        elseif ss[i] == "tshuss__zhuque" then
          room:setPlayerMark(p,"@tshu__xxiang",{"tshuxx__xingrima-bj","tshuxx__yihuoshe-bj"})
          room:handleAddLoseSkills(p,"tshu__lihuo",nil)
        elseif ss[i] == "tshuss__baihu" then
          room:setPlayerMark(p,"@tshu__xxiang",{"tshuxx__kuimulang-bj","tshuxx__canshuiyuan-bj"})
          room:handleAddLoseSkills(p,"tshu__duijin",nil)
        elseif ss[i] == "tshuss__xuanwu" then
          room:setPlayerMark(p,"@tshu__xxiang",{"tshuxx__weiyueyan-bj","tshuxx__doumuxie-bj"})
          room:handleAddLoseSkills(p,"tshu__shuikan",nil)
        end
    end
    --星宿
    local xing = {room.players[4],room.players[10]}
    local ii = 1
    for _, p in ipairs(xing) do
        local xboss = {}
        if gua[guax] == "tshu_gua_zhen" then
            xboss = {"tshuxx__jiaomujiao","tshuxx__kangjinlong"}
        elseif gua[guax] == "tshu_gua_li" then
            xboss = {"tshuxx__yihuoshe","tshuxx__xingrima"}
        elseif gua[guax] == "tshu_gua_dui" then
            xboss = {"tshuxx__kuimulang","tshuxx__canshuiyuan"}
        elseif gua[guax] == "tshu_gua_kan" then
            xboss = {"tshuxx__doumuxie","tshuxx__weiyueyan"}
        end
        room:setPlayerGeneral(p,xboss[ii], true, true)
        room:broadcastProperty(p, "role")
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "kingdom")
        ii = ii + 1
    end
    --星象
    if #renegade > 0 then
        for _, p in ipairs(renegade) do
            room:setPlayerGeneral(p,"tshuxx__xingxiang", true, true)
            room:broadcastProperty(p, "role")
            room:broadcastProperty(p, "general")
            room:broadcastProperty(p, "kingdom")
            room:addPlayerMark(p, MarkEnum.PlayerRemoved, 1)
        end
    end
    --玩家
    local gen = {}
    for _, p in ipairs(rebel) do
        local gens = room:getNGenerals(9)
        local skills = {{"tshu_yes1"},{"tshu_yes2"},{"tshu_yes3"},{"tshu_yes4"},{"tshu_yes5"},{"tshu_yes6"},{"tshu_yes7"},{"tshu_yes8"},{"tshu_yes9"}}
        if test and   room.settings.enableDeputy then
            table.insertIfNeed(gens,"mouxusheng")
            table.insert(skills,{"tshu_yes10"})
        end
        table.insert(gen,gens)
        p.request_data = json.encode({
            path = "packages/tshu/qml/ChooseGeneralSkillsBox.qml",
            data = {
              gens,skills, 1, 1, "#tshu__gen-choice", false
            },
          })
          p.default_reply = table.random(skills)
    end
      room:doBroadcastNotify("ShowToast", "选择你的起始武将。")
      room:notifyMoveFocus(rebel, "选择武将")
      room:doBroadcastRequest("CustomDialog",rebel)
      

      local g2 = 0
      for _, p in ipairs(rebel) do
        local g = p.reply_ready and json.decode(p.client_reply) or p.default_reply
        g2 = g2 + 1
        local gogen = gen[g2]
        g = table.concat(g)
        local num = string.sub(g, 9)
        num = (tonumber(string.match(num, "%d+")))
        g = gogen[num]
        table.removeOne(gogen,g)
        room:setPlayerGeneral(p, g, true, true)
        p.default_reply = ""
        room:returnToGeneralPile(gogen)

      end
      for _, p in ipairs(rebel) do
        room:broadcastProperty(p, "role")
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "kingdom")
        room:addPlayerMark(p,"@ganlu",1 + #renegade)
        room:handleAddLoseSkills(p,"tshu__qimen&",nil)
      end
      room:askForChooseKingdom(rebel)



    --PVEbuff
    for _, p in ipairs(rebel) do
      local choices = {"pvebuff1","pvebuff2","pvebuff3"}
      p.request_data = json.encode({choices, choices, "tshu__buff", "#pvebuff-choice",true})
    end
    room:notifyMoveFocus(room.alive_players,"tshu__buff")
    room:doBroadcastRequest("AskForChoice",rebel)

    for _, p in ipairs(rebel) do
      local choice
      if p.reply_ready then
        choice = p.client_reply
      else
        p.client_reply = "pvebuff2"
        choice = "pvebuff2"
      end
      room:sendLog{
        type = "#tshu__buff-quest",
        from = p.id,
        arg = choice,
      }
      if choice == "pvebuff1" then
        room:setPlayerMark(p,"tshu__buff1",1)
        room:setPlayerMark(p,"tshu__buff2",1)
      elseif choice == "pvebuff2" then
        room:setPlayerMark(p,"tshu__buff1",1)
        room:setPlayerMark(p,"tshu__buff3",1)
      elseif choice == "pvebuff3" then
        room:setPlayerMark(p,"tshu__buff3",1)
        room:setPlayerMark(p,"tshu__buff4",1)
      end
    end

    
    --将灵
    local jl = {"tshujl__zhugeguo","tshujl__lingjv","tshujl__zhouyu"}
    room:setBanner("@&tshu__jl",jl)
    local skills = {}
    for _, s in ipairs(jl) do
        table.insert(skills,{s})
    end
    for _, p in ipairs(rebel) do
      p.request_data = json.encode({
    path = "packages/tshu/qml/ChooseGeneralSkillsBox.qml",
    data = {
      jl,skills, 1, 1, "#jl-choice", false
    },
  })
  p.default_reply = table.random(skills)
  end
  room:notifyMoveFocus(rebel, "选择将灵")
  room:doBroadcastRequest("CustomDialog",rebel)
  

  for _, p in ipairs(rebel) do
    local jj = p.reply_ready and json.decode(p.client_reply) or p.default_reply
    room:notifySkillInvoked(p,table.concat(jj),"drawcard")
    for _, s in ipairs(Fk.generals[table.concat(jj)].skills) do
      p:broadcastSkillInvoke(s.name)
      break
    end
    room:setPlayerMark(p,table.concat(jj),1)
    room:setPlayerMark(p,"@&tshu__jlmark",{table.concat(jj)})
    p.default_reply = ""
  end
  end

  function tgong_logic:configureAI()
    for _, p in ipairs(self.room.players) do
      if p.id < 0 then
        p.ai = nil
        p.ai = LangAI:new(p)
      end
    end
  end

  return tgong_logic
end

Fk:loadTranslationTable{
    ["@tshu_guaxiang"] = "卦象",
    ["@[:]tshu__xingxiang"] = "星象",
    ["@tshu_guanxing"] = "观星",
    ["tshu_gua_zhen"] = "震",
    ["tshu_gua_li"] = "离",
    ["tshu_gua_dui"] = "兑",
    ["tshu_gua_kan"] = "坎",
    ["@tshu__4shen"] = "",
    ["tshu_east"] = "<font color='green'>东</font>",
    ["tshu_south"] = "<font color='red'>南</font>",
    ["tshu_west"] = "<font color='yellow'>西</font>",
    ["tshu_north"] = "<font color='blue'>北</font>",
    ["tshu_yes1"] = "选择",
    ["tshu_yes2"] = "选择",
    ["tshu_yes3"] = "选择",
    ["tshu_yes4"] = "选择",
    ["tshu_yes5"] = "选择",
    ["tshu_yes6"] = "选择",
    ["tshu_yes7"] = "选择",
    ["tshu_yes8"] = "选择",
    ["tshu_yes9"] = "选择",
    ["tshu_yes10"] = "选择",
}
local test = false

--游戏开始时机技能
local function restart(player)
  local skills = {}
  for _, s in ipairs(Fk.generals[player.general]:getSkillNameList()) do
    local s2 = Fk.skills[s]
    table.insertIfNeed(skills,s2)
    for _, s3 in ipairs(s2.related_skills) do
      table.insertIfNeed(skills,s3)
    end
  end
  if player.deputyGeneral and player.deputyGeneral ~= "" then
    for _, s in ipairs(Fk.generals[player.deputyGeneral]:getSkillNameList()) do
      local s2 = Fk.skills[s]
      table.insertIfNeed(skills,s2)
      for _, s3 in ipairs(s2.related_skills) do
        table.insertIfNeed(skills,s3)
      end
    end
  end
  for _, s in ipairs(skills) do
    if s:isInstanceOf(TriggerSkill) and type(s.events) == "table" and (table.contains(s.events,fk.GameStart) or table.contains(s.events, fk.GamePrepared)) then
      local events = {fk.GamePrepared, fk.GameStart}
      for i = #events, 1, -1 do
        if not table.contains(s.events, events[i]) then
          table.remove(events, i)
        end
      end
      for _, e in ipairs(events) do
        if s:triggerable(e, player, player, nil) then
          s:trigger(e, player, player, nil)
        end
      end
    end
  end
end


local function canreward(room)
  local a = room:getBanner("@tshu_pogua") or 0

  local rebel = {}
  for _, p in ipairs(room.players) do
    if p.role == "rebel" then
      table.insertIfNeed(rebel,p)
    end
  end
  local lord
  for _, p in ipairs(room.players) do
    if p.role == "lord" then
      lord = p
    end
  end
  local n = type(lord:getMark("@tshu__4shen")) == "table" and #lord:getMark("@tshu__4shen") or 0


  --单人福利

  for _, p in ipairs(room.players) do
    if p.role == "renegade" then
      for _, p2 in ipairs(rebel) do
        if not p2.dead then
            room:addPlayerMark(p2,"@ganlu",1)
        end
      end
    end
  end
  --选将


  for _, p in ipairs(rebel) do
    if not p.dead then
        room:addPlayerMark(p,"@ganlu",1)
    end
    
    room:resumePlayerArea(p, {Player.WeaponSlot, Player.ArmorSlot, Player.OffensiveRideSlot, Player.DefensiveRideSlot, Player.TreasureSlot, Player.JudgeSlot})
  end
  local gen = {}
  local g1 = 0
  for _, p in ipairs(rebel) do
    local gens = room:getNGenerals(9)
    local skills = {{"tshu_yes1"},{"tshu_yes2"},{"tshu_yes3"},{"tshu_yes4"},{"tshu_yes5"},{"tshu_yes6"},{"tshu_yes7"},{"tshu_yes8"},{"tshu_yes9"}}
        if test and   room.settings.enableDeputy then
            table.insertIfNeed(gens,"mouxusheng")
            table.insert(skills,{"tshu_yes10"})
        end
    table.insert(gen,gens)
    p.request_data = json.encode({
        path = "packages/tshu/qml/ChooseGeneralSkillsBox.qml",
        data = {
          gens,skills, 1, 1, "#tshu__gen-choice",true
        },
      })
      p.default_reply = ""
  end
  room:doBroadcastNotify("ShowToast", "你可以选择一个新武将，或保留当前武将")
  room:notifyMoveFocus(rebel, "选择武将")
  room:doBroadcastRequest("CustomDialog",rebel)
  

  local g2 = 0
  for _, p in ipairs(rebel) do
    local g = p.reply_ready and json.decode(p.client_reply) or p.default_reply
    room:revivePlayer(p, false)
    p:reset()
    --[[
    local nmark = {"tshu__tianshu","tshu__buff1","tshu__buff2","tshu__buff3","tshu__buff4","tshu__win","@ganlu","tgong__damage","tgong__draw","tgong__cover","tgong__shield","tgong__distance"}
      for name, _ in pairs(p.mark) do
        if not table.contains(nmark,name) then
          room:setPlayerMark(p, name, 0)
        end
      end]]
      g2 = g2 + 1
    local gogen = gen[g2]
    local change = false
    if g and g ~= "" and Fk:translate(table.concat(g)) ~= "" then
      g = table.concat(g)
      change = true
      local num = string.sub(g, 9)
      num = (tonumber(string.match(num, "%d+")))
      g = gogen[num]
      table.removeOne(gogen,g)
      local mark = (p:getMark("tgong_skill") ~= 0 and type(p:getMark("tgong_skill")) ) and p:getMark("tgong_skill") or {}
      local to_rm2 = table.filter(p.player_skills, function(s)
        return not s.attached_equip and not table.contains(mark,s.name) and  s.name[#s.name] ~= "&" -- 不是装备技和按钮的全图图了
       end)
      room:handleAddLoseSkills(p, table.concat(
         table.map(to_rm2, function(s) return "-" .. s.name end), "|"), nil, true)
      room:changeHero(p, g, false, false, true)
      room:setPlayerProperty(p, "kingdom", Fk.generals[g].kingdom)
      room:changeMaxHp(p,Fk.generals[g].maxHp*(1+a))
    end
    room:returnToGeneralPile(gogen)
    room:setPlayerProperty(p, "hp",p.maxHp)
    p:drawCards(5*a)
    if change then
      restart(p)
    end
    p.default_reply = ""
  end
  for _, p in ipairs(rebel) do
    room:broadcastProperty(p, "general")
    room:broadcastProperty(p, "kingdom")
  end
  room:askForChooseKingdom(rebel)


  --将灵
  local jl = {"tshujl__zhugeguo","tshujl__lingjv","tshujl__zhouyu"}
  local jj = 5 - n
  if jj > 0 then
    table.insertTable(jl,{"tshujl__caoying","tshujl__nianshou","tshujl__zhouyi"})
  end
  if jj > 1 then
    table.insertTable(jl,{"tshujl__xiaosha","tshujl__guansuo"})
  end
  if jj > 2 then
    table.insertTable(jl,{"tshujl__caochun","tshujl__guanyu"})
  end
  if jj > 3 then
    table.insertTable(jl,{"tshujl__zhaoxiang","tshujl__zhaoyun"})
  end
  room:setBanner("@&tshu__jl",jl)
  
  local skills = {}
  for _, s in ipairs(jl) do
    table.insert(skills,{s})
  end
  for _, p in ipairs(rebel) do
    for _, j in ipairs(jl) do
        room:setPlayerMark(p,j,0)
    end
  p.request_data = json.encode({
  path = "packages/tshu/qml/ChooseGeneralSkillsBox.qml",
  data = {
    jl,skills, 1, 1, "#jl-choice", false
  },
  })
  p.default_reply = table.random(skills)
  end
  room:doBroadcastNotify("ShowToast", "重新选择一个将灵")
   room:notifyMoveFocus(rebel, "选择将灵")
  room:doBroadcastRequest("CustomDialog",rebel)
 

  for _, p in ipairs(rebel) do
  local jj = p.reply_ready and json.decode(p.client_reply) or p.default_reply
  room:notifySkillInvoked(p,table.concat(jj),"drawcard")
  for _, s in ipairs(Fk.generals[table.concat(jj)].skills) do
    p:broadcastSkillInvoke(s.name)
    break
  end
  room:setPlayerMark(p,table.concat(jj),1)
  room:setPlayerMark(p,"@&tshu__jlmark",{table.concat(jj)})
  p.default_reply = ""
  end

  --额外技能
  local skill = {"jueqing","gundam__juejing","joy__shelie","ol_ex__yaowu","wuyan","dono__skill"}
  for _, p in ipairs(rebel) do
    local skill2 = table.simpleClone(skill)
    for _, s in ipairs(skill) do
      if s ~= "dono__skill" and p:hasSkill(s) then
        table.removeOne(skill2,s)
      end
    end
    p.request_data = json.encode({skill2, skill, "tgong_sskz", "#tgong_sskz",true})
  end
  room:notifyMoveFocus(room.alive_players,"tgong_sskz")
  room:doBroadcastRequest("AskForChoice",rebel)
  for _, p in ipairs(rebel) do
    local choice
      if p.reply_ready then
        choice = p.client_reply
      else
        p.client_reply = "dono__skill"
        choice = "dono__skill"
      end
    if choice == "dono__skill" then
      room:changeMaxHp(p,1)
      room:recover({
        who = p,
        num = 1,
        recoverBy = p,
        skillName = "tgong_sskz"
      })
      p:drawCards(5)
    else
      local mark = (p:getMark("tgong_skill") ~= 0 and type(p:getMark("tgong_skill")) ) and p:getMark("tgong_skill") or {}
      table.insertIfNeed(mark,choice)
      room:setPlayerMark(p,"tgong_skill",mark)
      room:handleAddLoseSkills(p,choice,nil)
    end
    room:sendLog{
      type = "tgong_sskz",
      from = p.id,
      arg = choice,
    }
  end

  --天宫增益
  local buff = {"tgong__damage","tgong__draw","tgong__cover","tgong__shield","tgong__distance"}
  for _, p in ipairs(rebel) do
    p.request_data = json.encode({buff, buff, "tgong_sskz", "#tgong_sskz2",true})
  end
  room:notifyMoveFocus(room.alive_players,"tgong_sskz")
  room:doBroadcastRequest("AskForChoice",rebel)
  for _, p in ipairs(rebel) do
    local choice
      if p.reply_ready then
        choice = p.client_reply
      else
        local r = table.random(buff)
        p.client_reply = r
        choice = r
      end
    room:addPlayerMark(p,choice,1)
    room:sendLog{
      type = "tgong_sskz",
      from = p.id,
      arg = choice,
    }
  end

end
Fk:loadTranslationTable{
  ["dono__skill"] = "放弃技能",
  [":dono__skill"] = "放弃技能，你会增加一点体力上限回复一点体力并摸一定数量的牌。",
  ["tgong_sskz"] = "神兽馈赠",
  ["#tgong_sskz"] = "你可以获得一个特殊技能。",
  ["#tgong_sskz2"] = "选择一个天宫增益",
  ["tgong__damage"] = "<font color='red'>伤害增加</font>",
  [":tgong__damage"] = "<font color='red'>造成伤害+1。</font>",
  ["tgong__draw"] = "<font color='yellow'>额外摸牌。</font>",
  [":tgong__draw"] = "<font color='yellow'>准备阶段和结束阶段额外摸一张牌。</font>",
  ["tgong__cover"] = "<font color='green'>回复体力。</font>",
  [":tgong__cover"] = "<font color='green'>回合开始时额外回复两点体力。</font>",
  ["tgong__shield"] = "<font color='blue'>加持护盾</font>",
  [":tgong__shield"] = "<font color='blue'>每回合结束时将护盾额外恢复至1点。</font>",
  ["tgong__distance"] = "<font color='yellow'>加持马术</font>",
  [":tgong__distance"] = "<font color='yellow'>计算与其他角色距离-1。</font>",
}

local qimen = fk.CreateActiveSkill{
  name = "tshu__qimen&",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 0,
  target_filter = Util.FalseFunc,
  prompt = "每局游戏限用三次，逆转一次“星象”并重置“观星”。",
  can_use = function(self, player)
      return  player:usedSkillTimes(self.name, Player.HistoryGame) < 3
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    --观星
    local h = {"","","",""}
    local ran = math.random(1,10)
    if ran == 1 then
      h[3] = table.random({"装备","基本","锦囊"})
    elseif ran <= 4 then
      h[4] = table.random({"jink","fire__slash","slash","thunder__slash","peach","analeptic","iron_chain","fire_attack","duel","lightning","ex_nihilo","nullification","savage_assault","archery_attack"})
    elseif ran <= 7 then
      h[1] = table.random({"log_club","log_heart","log_diamond","log_spade"})
    else
      h[2] = math.random(1,13)
    end
    room:setBanner("@tshu_guanxing",h)

      room:setBanner("tshu_guanxing_n",0)
      local xingx = {"tshu__north","tshu__west","tshu__south","tshu__east","tshu__north"}
      for i = 1, 4, 1 do
        if room:getBanner("@[:]tshu__xingxiang") == xingx[i] then
            room:setBanner("@[:]tshu__xingxiang",xingx[i+1])
            room:doBroadcastNotify("ShowToast", "星象变更为“"..Fk:translate(xingx[i+1]).."”")
            break
        end
      end
  end,
}
local qimen_distance = fk.CreateDistanceSkill{
  name = "#tshu__qimen_distance",
  frequency = Skill.Compulsory,
  correct_func = function(self, from, to)
    if from.role == "rebel" and from:hasSkill(self)   then
      return -from:getMark("tgong__distance")
    end
  end,
}
qimen:addRelatedSkill(qimen_distance)
Fk:addSkill(qimen)
Fk:loadTranslationTable{
  ["tshu__qimen&"] = "奇门",
  [":tshu__qimen&"] = "每局游戏限用三次，将“星象”逆转为上一个“星象”并重置“观星”任务。",
}


local tgong_rule = fk.CreateTriggerSkill{
  name = "#tgong_rule",
  priority = 0.001,
  refresh_events = {fk.GameStart,fk.DrawInitialCards,fk.CardUsing,fk.CardResponding,fk.GameOverJudge,fk.BuryVictim,fk.RoundEnd,fk.AskForPeachesDone,"fk.tgong_pogua",fk.TurnStart,fk.TurnEnd,fk.EventPhaseStart,fk.DamageCaused},
  can_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing or event == fk.CardResponding then
      if room:getBanner("@tshu_guanxing") and type(room:getBanner("@tshu_guanxing")) == "table" then
        local a =  room:getBanner("@tshu_guanxing") 
        if a[4] and a[4] ~= "" then
          return target and data.card and data.card.name == a[4]
        elseif a[3] and a[3] ~= "" then
          return target and data.card and ((data.card.type == Card.TypeEquip and a[3] == "装备") or (data.card.type == Card.TypeTrick and a[3] == "锦囊") or (data.card.type == Card.TypeBasic and a[3] == "基本"))
        elseif a[1]  and a[1] ~= ""  then
          return target and data.card  and data.card:getSuitString(true) == a[1]
        elseif  a[2] and a[2] ~= "" then
          return target and data.card and data.card.number == a[2]
        end
      end
    elseif event == fk.AskForPeachesDone then
      return target == player and player.role == "rebel" and player.hp < 1
    elseif event == fk.TurnStart then
      return target == player and player:getMark("tgong__cover") > 0 and player:isWounded()
    elseif event == fk.EventPhaseStart then
      return target == player and player:getMark("tgong__draw") > 0 and (player.phase == Player.Start or player.phase == Player.Finish)
    elseif event == fk.DamageCaused then
      return target == player and player:getMark("tgong__damage") > 0
    elseif event == fk.TurnEnd then
      return target == player and player:getMark("tgong__shield") > 0 and player.shield < player:getMark("tgong__shield")
    elseif event == fk.DrawNCards then
      return target == player and player.role ~= "rebel"
    elseif event == fk.RoundEnd then
      return player.role == "lord" and player:usedSkillTimes(self.name, Player.HistoryRound) == 0
    else
      return target == player
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local body
    local nmark = {"@&tshu__jlmark","tshu__tianshu","tshu__buff1","tshu__buff2","tshu__buff3","tshu__buff4","tshu__win","@ganlu","tgong__damage","tgong__draw","tgong__cover","tgong__shield","tgong__distance"}
    if room:getBanner("@&tshu__jl")  and #room:getBanner("@&tshu__jl")  > 0 then
      local gjl = room:getBanner("@&tshu__jl") 
      table.insertTable(nmark,gjl)
    end
    if event == fk.BuryVictim or event == fk.GameOverJudge then
      body = room:getPlayerById(data.who)
    end
    if event == fk.DrawInitialCards then
      if player.role == "renegade" then
        data.num = 0
      elseif player.role == "rebel" then
        data.num = 5
      else
        data.num = 5
      end
    elseif event == fk.GameOverJudge then
      room:setTag("SkipGameRule", true)
      if  body.role == "loyalist"  then return end
      if  body.role == "renegade"  then  return end
      local nowin = false
      for _, p in ipairs(room.alive_players) do
        if p.role == "rebel" then
          nowin = true
        end
        if nowin then break end
      end
      if nowin and body.role == "rebel" then 
        return
      end
      if body.role == "lord"  then
        room:doBroadcastNotify("ShowToast", "恭喜！“四象天宫”模式胜利！")
        room:doBroadcastNotify("ShowToast", "恭喜！“四象天宫”模式胜利！！")
        room:doBroadcastNotify("ShowToast", "恭喜！“四象天宫”模式胜利！！！")
        room:gameOver("rebel")
      else
        room:gameOver("lord")
      end
      return true
    elseif event == fk.GameStart then
      local n = #room.players
      local bots_t = {}
      local players_t = {}
      for i = 1, n do
        local p = room.players[i]
        if p.id < 0 then
          table.insert(bots_t,{p.id,i})
        end
        if p.id > 0 then
          table.insert(players_t,{p.id,i})
        end
      end
      if #players_t  > 3 then
        room:doBroadcastNotify("ShowToast", "请保证真人不超过3名")
        room:gameOver("")
        return
      end
      --moveSeats(room)
      room:delay(300)
      room:doBroadcastNotify("ShowToast", "使用或打出5张“观星”卡即可令“星象”更替。")
      room:doBroadcastNotify("ShowToast", "击杀“星宿”来解除神兽的保护。")
      room:doBroadcastNotify("ShowToast", "注意避免触发 少昊 的反伤技能。")
      room:delay(1000)
      ----电脑死亡
    elseif event == fk.BuryVictim and  body.role == "loyalist" and table.contains({"tshuss__qinglong","tshuss__zhuque","tshuss__baihu","tshuss__xuanwu"},body.general) then
      room:setTag("SkipGameRule", true)
      body:bury()
      canreward(room)
      ---玩家死亡换将
    elseif event == fk.BuryVictim and body.role == "rebel" then
      room:setTag("SkipGameRule", true)
      body:setCardUseHistory("")
      body:setSkillUseHistory("")
      body:throwAllCards()
      for name, _ in pairs(body.mark) do
        if not table.contains(nmark,name) then
          room:setPlayerMark(body, name, 0)
        end
      end
      body:clearPiles()
      body:reset()
      room:doBroadcastNotify("ShowToast", "击杀一个神兽后复活。")
    elseif event == fk.AskForPeachesDone then
        if player:getMark("@ganlu") > 0 then
            room:removePlayerMark(player,"@ganlu",1)
            room:notifySkillInvoked(player, "甘露", "support")
            room:recover({
                who = player,
                num = math.min(5, player.maxHp) - player.hp,
                recoverBy = player,
                skillName = self.name,
              })
            player:drawCards(5, self.name)
        else
            local can = false
            for _, p in ipairs(room.alive_players) do
                if can  then break end
                if p.role == "rebel" and p:getMark("@ganlu") > 0 then
                    can = room:askForSkillInvoke(p,"甘露",nil,"是否消耗一枚“甘露”拯救 %dest ？::"..player.id)
                end
                if can then
                    room:removePlayerMark(p,"@ganlu",1)
                    room:notifySkillInvoked(player, "甘露", "support")
                    room:recover({
                        who = player,
                        num = math.min(5, player.maxHp) - player.hp,
                        recoverBy = player,
                        skillName = self.name,
                        })
                    player:drawCards(5, self.name)
                    break
                end
            end
        end
    elseif event == fk.DamageCaused then
        data.damage = data.damage + player:getMark("tgong__damage")
    elseif event == fk.DrawNCards then
        data.n = data.n + (room:getBanner("@tshu_pogua") or 0)*2
    elseif event == fk.RoundEnd then
        local xx = {{"tshuxx__jiaomujiao","tshuxx__kangjinlong"},{"tshuxx__yihuoshe","tshuxx__xingrima"},{"tshuxx__kuimulang","tshuxx__canshuiyuan"},{"tshuxx__doumuxie","tshuxx__weiyueyan"},{"tshuxx__jiaomujiao","tshuxx__kangjinlong"}}
        local xmark = {{"tshuxx__jiaomujiao-bj","tshuxx__kangjinlong-bj"},{"tshuxx__yihuoshe-bj","tshuxx__xingrima-bj"},{"tshuxx__kuimulang-bj","tshuxx__canshuiyuan-bj"},{"tshuxx__doumuxie-bj","tshuxx__weiyueyan-bj"},{"tshuxx__jiaomujiao-bj","tshuxx__kangjinlong-bj"}}
        local gua = {"tshu_gua_zhen","tshu_gua_li","tshu_gua_dui","tshu_gua_kan","tshu_gua_zhen"}
        local xingx = {"tshu__east","tshu__south","tshu__west","tshu__north","tshu__east"}
        local a = room:getBanner("@tshu_pogua") or 0
        local m = 0
        for i = 1, 4, 1 do
            if room:getBanner("@tshu_guaxiang") == gua[i] then
                room:setBanner("@tshu_guaxiang",gua[i+1])
                room:doBroadcastNotify("ShowToast", "本轮卦象：“"..Fk:translate(gua[i+1]).."”")
                m = i+1
                break
            end
        end
        for i = 1, 4, 1 do
          if room:getBanner("@[:]tshu__xingxiang") == xingx[i] then
              room:setBanner("@[:]tshu__xingxiang",xingx[i+1])
              room:doBroadcastNotify("ShowToast", "星象变更为“"..Fk:translate(xingx[i+1]).."”")
              break
          end
        end

        --观星
        local h = {"","","",""}
        local ran = math.random(1,10)
        if ran == 1 then
          h[3] = table.random({"装备","基本","锦囊"})
        elseif ran <= 4 then
          h[4] = table.random({"jink","fire__slash","slash","thunder__slash","peach","analeptic","iron_chain","fire_attack","duel","lightning","ex_nihilo","nullification","savage_assault","archery_attack"})
        elseif ran <= 7 then
          h[1] = table.random({"log_club","log_heart","log_diamond","log_spade"})
        else
          h[2] = math.random(1,13)
        end
        room:setBanner("@tshu_guanxing",h)

        local ii = 1
        for _, p in ipairs({room.players[4],room.players[10]}) do
            local to_rm = table.filter(p.player_skills, function(s)
                return not s.attached_equip and s.name[#s.name] ~= "&" -- 不是装备技和按钮的全图图了
               end)
            room:handleAddLoseSkills(p, table.concat(
                 table.map(to_rm, function(s) return "-" .. s.name end), "|"), nil, true)
            room:resumePlayerArea(p, {Player.WeaponSlot, Player.ArmorSlot, Player.OffensiveRideSlot, Player.DefensiveRideSlot, Player.TreasureSlot, Player.JudgeSlot}) -- 全部恢复
        
            room:changeHero(p,xx[m][ii], false, false, true)
            local yes = false
            for _, p2 in ipairs({room.players[5],room.players[6],room.players[8],room.players[9]}) do
                local mark = type(p2:getMark("@tshu__xxiang")) == "table" and p2:getMark("@tshu__xxiang") or {}
                if table.contains(mark,xmark[m][ii]) then
                  yes = true
                end
            end
            room:revivePlayer(p, false)
            room:setPlayerProperty(p, "kingdom", Fk.generals[xx[m][ii]].kingdom)
            room:changeMaxHp(p,Fk.generals[xx[m][ii]].maxHp*a)
            if yes then
              room:setPlayerProperty(p, "hp", p.maxHp)
              p:drawCards(5*(1+a))
            else
              room:killPlayer({who = p.id})
            end
            ii = ii + 1
        end
    elseif event == "fk.tgong_pogua" then
        room:setBanner("@tshu_pogua",(room:getBanner("@tshu_pogua") or 0) + 1) 
        for _, p in ipairs(room.alive_players) do
          room:changeMaxHp(p,Fk.generals[p.general].maxHp)
          room:setPlayerProperty(p, "hp", p.maxHp)
          p:drawCards(5)
        end
    elseif event == fk.TurnStart then
      room:recover({
        who = player,
        num = math.min(player.maxHp-player.hp,2*player:getMark("tgong__cover")),
        recoverBy = player,
        skillName = self.name
      })
    elseif event == fk.EventPhaseStart then
      player:drawCards(player:getMark("tgong__draw"),self.name)
    elseif event == fk.TurnEnd then
      player.room:changeShield(player, player:getMark("tgong__shield") - player.shield)
    elseif event == fk.CardUsing or event == fk.CardResponding then
      room:setBanner("tshu_guanxing_n",(room:getBanner("tshu_guanxing_n") or 0) + 1)
      --local a,b,c,d = "","","",""
      --观星
      local h = {"","","",""}
      local ran = math.random(1,10)
      if ran == 1 then
        h[3] = table.random({"装备","基本","锦囊"})
      elseif ran <= 4 then
        h[4] = table.random({"jink","fire__slash","slash","thunder__slash","peach","analeptic","iron_chain","fire_attack","duel","lightning","ex_nihilo","nullification","savage_assault","archery_attack"})
      elseif ran <= 7 then
        h[1] = table.random({"log_club","log_heart","log_diamond","log_spade"})
      else
        h[2] = math.random(1,13)
      end
      room:setBanner("@tshu_guanxing",h)

      --判断星象
      if (room:getBanner("tshu_guanxing_n") or 0) >= 5 then
        room:setBanner("tshu_guanxing_n",0)
        local xingx = {"tshu__east","tshu__south","tshu__west","tshu__north","tshu__east"}
        for i = 1, 4, 1 do
          if room:getBanner("@[:]tshu__xingxiang") == xingx[i] then
              room:setBanner("@[:]tshu__xingxiang",xingx[i+1])
              room:doBroadcastNotify("ShowToast", "星象变更为“"..Fk:translate(xingx[i+1]).."”")
              break
          end
        end
      end
    end
  end,
}

local tgong_mode = fk.CreateGameMode{
  name = "tgong_mode",
  minPlayer = 10,
  maxPlayer = 10,
  rule = tgong_rule,
  logic = tgong_getLogic,
  surrender_func = function(self, playedTime)
    return { { text = "tshu_allcan", passed = true } }
  end,
}

Fk:loadTranslationTable{
  ["tgong_mode"] = "四象天宫",
  ["@tshu_pogua"] = "破卦",
  [":tgong_mode"] = desc_tgong,
}

return tgong_mode
